package com.dao;

import com.po.chat;
import com.utils.JDBCUnits;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Stack;

public class ChatDao {
    /**
     * 获取和某个好友的聊天记录
     * @param id 自己的id
     * @param friend_id 朋友的id
     * @return
     */
    public static Stack<chat> getFriendChat(int id, int friend_id){
        Stack<chat> myChat = new Stack<>();
        Connection c = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            c = JDBCUnits.getConnectino();
            String sql = "select * from charwithfriend where (id=? and friend_id=?) or (id=? and friend_id=?) group by chatTime asc";
            ps = c.prepareStatement(sql);
            ps.setInt(1,id);
            ps.setInt(2,friend_id);
            ps.setInt(3,friend_id);
            ps.setInt(4,id);
            rs = ps.executeQuery();
            while(rs.next()){
                chat ch = new chat();
                if(rs.getInt("id")==id){
                    ch.setWho(1);
                    ch.setChatContent(rs.getString("chatContent"));
                    myChat.push(ch);
                }else{
                    ch.setWho(0);
                    ch.setChatContent(rs.getString("chatContent"));
                    myChat.push(ch);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUnits.close(c,ps,rs);
        }

        return myChat;
    }
}
